package com.itcast.cn.request;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;

/**
 * <p>request对象的学习</p>
 *
 * @author hyatt 2022/1/17 17:44
 * @version 1.0
 */
@WebServlet("/request1")
public class RequestTest extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 请求访问：http://localhost:8080/request1?username=zhangsan&password=1234
        // String getMethod()：获取请求方式：
        String method = req.getMethod();
        // GET
        System.out.println(method);
        // String getContextPath()：获取虚拟目录(项目访问路径)
        String contextPath = req.getContextPath();
        // 为空 因为插件那边没有配置地址
        System.out.println(contextPath);
        // StringBuffer getRequestURL(): 获取URL(统一资源定位符)
        StringBuffer requestURL = req.getRequestURL();
        // http://localhost:8080/request1
        System.out.println(requestURL.toString());
        // String getRequestURI()：获取URI(统一资源标识符)
        String requestURI = req.getRequestURI();
        // /request1
        System.out.println(requestURI);
        // String getQueryString()：获取请求参数（GET方式）： username=zhangsan
        String queryString = req.getQueryString();
        // username=zhangsan&password=1234
        System.out.println(queryString);

        // 获取请求头的数据
        String header = req.getHeader("user-agent");
        System.out.println(header);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        BufferedReader reader = req.getReader();
        String s = reader.readLine();
        System.out.println(s);
        // 一次请求结束后自动关闭，所以这里可以不用关闭
        reader.close();
    }
}
